import { defineStore } from 'pinia';
import {
  LoginData,
  login as userLogin,
  logout as userLogout,
  RegisterData,
  register as userRegister,
  resetPassword,
  ResetPasswordData,
} from '@/api/user';
import { setToken, clearToken, setUserInfo, getUserInfo } from '@/utils/auth';
import { UserState } from './types';
import { useConfigStore, useMenuStore } from '@/store';

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    id: 0,
    role_ids: '',
    account: '',
    nickname: '',
    phone: '',
    email: '',
    avatar_id: '',
    introduce: '',
    login_number: 0,
    login_last_ip: '',
    login_last_ip_region: '',
    login_last_time: '',
    is_super: 0,
    is_disable: 0,
    create_time: '',
    update_time: '',
    delete_time: '',
    token: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    }
  },

  actions: {

    // 设置用户信息
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // 设置用户头像
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },

    // 重置用户的信息
    resetInfo() {
      this.$reset();
    },

    // 获取用户的信息
    async info() { // TODO 获取用户信息
      const res = await getUserInfo();
      this.setInfo(res);
    },

    // 账号密码登录
    async login(loginForm: LoginData) {
      try { // TODO  登录接口
        const res = await userLogin(loginForm);
        setToken(res['token']);
        delete res['token'];
        setUserInfo(res);
      } catch (err) {
        clearToken();
        throw err;
      }
    },

    // 注册账号
    async register(registerForm: RegisterData) {
      await userRegister(registerForm);
    },

    // 重置密码
    async resetPassword(ResetPasswordForm: ResetPasswordData) {
      await resetPassword(ResetPasswordForm);
    },

    // 退出系统
    async logout() {
      await userLogout();
      this.clearCache();
    },

    //  清理缓存
    async clearCache() {
      const menuStore = useMenuStore();
      const configStore = useConfigStore();
      this.resetInfo();
      setUserInfo('');
      clearToken();
      menuStore.cleanData();
      configStore.cleanData();
    },
  },
});
